var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,upload = layui.upload
    ,userphotos="",
    form = layui.form,$ = layui.jquery,id=getQueryVariable("id"),isUsed = getQueryVariable("isUsed"),
img_count=0,file_count=0,maincode="",imgs=[],wjs=[];
var selectdata=[];
queryPid();
var tpdata = [{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
}];
var fjdata = [{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
}];

var dw=getdictionary(3,10);//单位
var cgbz=getdictionary(5,14);//采购币种
var gys=getgys();//供应商集合
var fjCode="";//附件规格型号
var cataCodeName=JSON.parse(window.sessionStorage.getItem("cataCodeName"));//没用
var  cataCode=JSON.parse(window.sessionStorage.getItem("cataCode"));//被修改产品的目录编码
let cataCodeMo=window.sessionStorage.getItem('cataCodeMo');//主页 左边树被点击目录的编码

var code="";
if(id !=""){
    code=JSON.parse(window.sessionStorage.getItem("code"));//产品编码
}
var hs=getdictionary(3,8);//海关
$("input[name='vatRate']").attr("readOnly",true);
$("input[name='taxreRates']").attr("readOnly",true);
$("input[name='importTariff']").attr("readOnly",true);

var hsselect=$("select[name='hgCode']");//客户等级
hsselect.append(getoptionHs(hs));

form.on("select(hgCodeFilter)", function(data){
    var hg=data.value;
    for(var i=0;i<hs.length;i++){
        if(hg==hs[i].code){
            $("input[name='vatRate']")[0].value=hs[i].vatRate;
            $("input[name='taxRate']")[0].value=hs[i].taxRate;
            $("input[name='importTariff']")[0].value=hs[i].importTariff;
            break;
        }else{
            $("input[name='vatRate']")[0].value="";
            $("input[name='taxRate']")[0].value="";
            $("input[name='importTariff']")[0].value="";
        }
    }
    form.render();
});


//目录树
let productTreeList=[];
//产品目录
let treeList=toTree(selectdata);
if(treeList){
    let productTree = getAllJson(treeList);
    productTreeList=getxmselect("#directory","cataCode", productTree)
}else {
    productTreeList=getxmselect("#directory","cataCode", [])
}

//监听上级目录下拉框
form.on("select(upDirectoryFilter)", function(data){
    $("#directory").empty();
    let code=data.value;
    getDirectory(code);
})


function getUpDirectory() {
    queryPid();
    $("#upDirectory").append("<option value=''></option>");
    for (var i = 0; i < selectdata.length; i++) {
        $("#upDirectory").append("<option value=\"" + selectdata[i].code +  "\">" + selectdata[i].name + "</option>");
    }
}
//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
function getDirectory(code) {
    let upDirectoryTemp;

        for (let i in selectdata) {
            if (code==selectdata[i].code){
                upDirectoryTemp=selectdata[i];
            }
        }
    if (!isEmpty(upDirectoryTemp)){
        let pidArr=[]
        for (var i = 0; i < selectdata.length; i++) {
            if (upDirectoryTemp.id==selectdata[i].pid){
                pidArr.push(selectdata[i]);
            }
        }
        if (pidArr.length<=0){
            pidArr.push(upDirectoryTemp);
        }
        for (let i in pidArr) {
            $("#directory").append("<option value=\"" + pidArr[i].code +  "\">" + pidArr[i].name + "</option>");
        }

        form.render();
    }
}

//新增:true 修改:false
let addFlag = true;
layer.ready(function () {
    if(!isEmpty(id)){
        //修改
        addFlag = false;
        if(!isEmpty(isUsed)){
            $('#editor-form').find('input,textarea,select').attr('disabled',true);
            document.getElementById("imgId").style.display = "none";
            document.getElementById("annexId").style.display = "none";
            form.render();
        }
    }
});

//表单初始值，修改时调用
if(id!=""){
    $("input[name='code']").attr("readOnly",true);
    var obj=init(id);//回显
    cataCode=obj.cataCode;
    form.val("editor-form",{
        "code":obj.code,
        "chinaName":obj.chinaName,
        "englishName":obj.englishName,
        "hgCode":obj.hgCode,
        "customerCode":obj.customerCode,
        "remark":obj.remark
    });
    productTreeList.setValue([ cataCode ]);

    var hgname="";
    var hg=obj.hgCode;
    for(var i=0;i<hs.length;i++){
        if(hg==hs[i].code){
            hgname=hs[i].name;
            $("input[name='vatRate']")[0].value=hs[i].vatRate;
            $("input[name='taxRate']")[0].value=hs[i].taxRate;
            $("input[name='importTariff']")[0].value=hs[i].importTariff;
            break;
        }else{
            $("input[name='vatRate']")[0].value="";
            $("input[name='taxRate']")[0].value="";
            $("input[name='importTariff']")[0].value="";
        }
    }

    tpdata=JSON.parse(obj.img);

    for(var i = 0;i<tpdata.length;i++){
        img_count ++;
        var newImg ='<div class="img_tj">'+
            '<div class="img_wdiv"><img src="'+tpdata[i]+'" id="imgUpload_'+img_count+'"></div>'+
            '<div class="de_div">'+
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_'+img_count+'"></i>'+
            '</div>'+
            '</div>';
        $('#addimgdiv').append(newImg);
        imgs.push(tpdata[i]);
        uploadImgRender("#imgUpload_"+img_count,"#imgUpload_sc_"+img_count);
    }
    fjdata=JSON.parse(obj.wj);
    for(var i = 0;i<fjdata.length;i++){
        file_count ++;
        var filename=fjdata[i].split("filename=")[1];
        var filenames=fjdata[i].split("pathname=")[1].split("&filename=");
        var pathA=filenames[0];//"c:/a/a/"
        var fnas=filenames[1].split("&originalFileName=");
        filename=fnas[1];
        pathA=pathA+"/"+fnas[0];
        var newFile ='<div class="img_tj">'+
            '<div class="file_wdiv"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="'+filename+'" id="file_span'+file_count+'" download="'+filename+
            '" href="javascript:void(0);" onclick="onLineFile(\''+pathA+'\');">'+filename+'</a>' +
            '<a type="button" class="layui-btn" id="fileUpload_'+file_count+'"><i class="layui-icon"></i>上传附件</a></div>'+
            '<div class="de_div">'+
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;" ' +
            'id="fileUpload_sc_'+file_count+'"></i>'+
            '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;" onclick="downFileLoadNew(\''+filename+'\',\''+pathA+'\');"></i>'+
            '</div>'+
            '</div>';
        $('#addfilediv').append(newFile);
        wjs.push(fjdata[i]);
        uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count);
    }

    form.render();
}else{
    form.val("editor-form",{
        "code":"",
        "chinaName":"",
        "englishName":"",
        "hgCode":"",
        "customerCode":"",
        "remark":""
    });
    $("input[name='vatRate']")[0].value="";
    $("input[name='taxRate']")[0].value="";
    $("input[name='importTariff']")[0].value="";
    $('#addimgdiv').html("");
    $('#addfilediv').html("");

    productTreeList.setValue([cataCode]);
    form.render();
}

function init(id){
    var obj=[];
    $.ajax({
        type : 'get',
        data:{"id":id},
        url:'productmaininfo/queryById',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
               obj=da.data;
            }
        }
    });
    return obj;
}
//---规格查询
table.render({
    elem: '#productselect'
    ,type:"get"
    ,url:"productfjinfo/selectByPage"
    ,where:{
        "code":code
    }
    ,toolbar: '#producttoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'code', title: '规格编码',event:'specificationcoding', width: 120, sort: true}
        ,{field:'ge', title: '规格说明', width: 120, sort: true}
        ,{field:'chinaRemark', title:'中文描述', width: 120, sort: true}
        ,{field:'englishRemark', title:'英文描述', width: 120, sort: true}
        ,{field:'bzsm', title:'每托箱数', width: 120, sort: true}
        ,{field:'cpjz', title:'净重KGS/CTN', width: 120, sort: true}
        ,{field:'cpmz', title:'毛重KGS/CTN', width: 120, sort: true}
        ,{field:'colour', title: '颜色', width: 120, sort: true}
        ,{field:'dw', title:'单位', width: 120, sort: true}
        ,{field:'wbzc', title:'外包装长mm', width: 120, sort: true}
        ,{field:'wbzk', title:'外包装宽mm', width: 120, sort: true}
        ,{field:'wbzg', title:'外包装高mm', width: 120, sort: true}
        ,{field:'wbzsl', title:'每箱数量', width: 120, sort: true}
        ,{field:'tj', title:'体积', width: 120, sort: true}
        ,{field:'hq40zl', title:'40HQ装量', width: 120, sort: true}
        ,{field:'gp20', title:'20GP', width: 120, sort: true}
        ,{field:'gp40', title:'40GP', width: 120, sort: true}
        ,{field:'lclpx', title:'LCL拼箱', width: 120, sort: true}
        ,{field:'categoryName', title:'垫片种类编码', width: 120, sort: true}
        ,{field:'categoryCode', title:'垫片种类编码', hide: true,  width: 120, sort: true}
        ,{field:'moldCategoryName', title:'垫片种类', width: 120, sort: true}
        ,{field:'moldCategoryCode', title:'垫片种类编码', hide: true,  width: 120, sort: true}
        ,{field:'firstCategoryName', title:'垫片耳朵', width: 120, sort: true}
        ,{field:'firstCategoryCode', title:'垫片耳朵编码', hide: true,  width: 120, sort: true}
        ,{field:'secondaryCategoryName', title:'垫片特殊参数', width: 120, sort: true}
        ,{field:'secondaryCategoryCode', title:'垫片特殊参数编码', hide: true,  width: 120, sort: true}
        ,{field:'threeCategoryName', title:'垫片尺寸', width: 120, sort: true}
        ,{field:'threeCategoryCode', title:'垫片尺寸编码', hide: true,  width: 120, sort: true}
        ,{field:'craftName', title:'印刷稿件3位简码', width: 120, sort: true}
        ,{field:'craftCode', title:'印刷稿件3位简码编码', hide: true,  width: 120, sort: true}
        ,{field:'colorOrderNumberName', title:'颜色订货号', hide: true, width: 120, sort: true}
        ,{field:'colorOrderNumberCode', title:'颜色订货号编码', hide: true,  width: 120, sort: true}
        ,{field:'specialNeedsName', title:'特殊需求(垫片)', width: 120, sort: true}
        ,{field:'specialNeedsCode', title:'特殊需求(垫片)编码', hide: true,  width: 120, sort: true}
        ,{fixed:'right', width:150, align:'center', toolbar: '#productup', title:'操作'}
    ]]
    ,id: 'producttableid'
    ,page: true
    ,height:300
    ,done:function(res, curr, count){
        $("[data-field = 'cgbz']").children().each(function(){
            for(var i=0;i<cgbz.length;i++){
                if($(this).text()==cgbz[i].code){
                    $(this).text(cgbz[i].name);
                }
            }
        })
        $("[data-field = 'dw']").children().each(function(){
            for(var i=0;i<dw.length;i++){
                if($(this).text()==dw[i].code){
                    $(this).text(dw[i].name);
                }
            }
        })
        $("[data-field = 'gys']").children().each(function(){
            for(var i=0;i<gys.length;i++){
                if($(this).text()==gys[i].code){
                    $(this).text(gys[i].name);
                }
            }
        })

    }
});
//规格型号新增、删除
table.on('toolbar(producttable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'new':
            if(id =="" ){
                layer.msg("请先保存产品主信息");
                return false;
            }
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/BasicData/tpl/addPartsSpec.jsp'
            });
            break;
        case 'delet':
            let data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    if(delfjinfo(delList)){
                        layer.msg('删除成功');
                        layer.close(index);
                        refrash();
                    }else{
                        layer.msg('删除失败');
                    }
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

//行内修改、删除
table.on('tool(producttable)', function(obj) {
    let data = obj.data;
    fjCode=data.code;
    if (obj.event === 'productup') {
        layer.open({
            type: 2,
            area: ['1488px', '800px'],
            content: 'views/jsp/BasicData/tpl/addPartsSpec.jsp?id=' + obj.data.id+'&oldCode='+obj.data.code
        });
    } else if (obj.event === 'productde') {
        layer.confirm('真的删除行么', function (index) {
            var delList = [];
            delList.push(data.id);
            if (delfjinfo(delList)) {
                layer.msg('删除成功');
                layer.close(index);
                refrash();
            } else {
                layer.msg('删除失败');
            }
        });
    } else if (obj.event === 'specificationcoding') {
        $("#hidden").show();
        table.render({
            elem: '#asupplierselect'
            , data:[]
            , type: "get"
            , url: "productfjgysbak/selectByPage"
            , toolbar: '#asuppliertoolbar'
            , where: {
                "productCode": code,
                "fjCode": data.code
            } //查询的产品ID，条件
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'code', title: '供应商', sort: true}
                , {field: 'fob', title: '含税FOB价', sort: true}
                , {field: 'cshh', title: '未税FOB价', sort: true}
                , {field: 'cgbz', title: '采购币种', sort: true}
                , {field: 'cgcb', title: '含税出厂价', sort: true}
                , {field: 'catalog', title: '未税出厂价', sort: true}
                , {field: 'createDate', title: '创建日期', sort: true}
                , {field: 'updateDate', title: '修改日期', sort: true}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#asupplierup', title: '操作'}
            ]]
            , id: 'asuppliertableid'
            , page: true
            , height: 300
            , done: function (res, curr, count) {
                $("[data-field = 'cgbz']").children().each(function () {
                    for (var i = 0; i < cgbz.length; i++) {
                        if ($(this).text() == cgbz[i].code) {
                            $(this).text(cgbz[i].name);
                        }
                    }
                })

                $("[data-field = 'code']").children().each(function () {
                    for (var i = 0; i < gys.length; i++) {
                        if ($(this).text() == gys[i].code) {
                            $(this).text(gys[i].name);
                        }
                    }
                })

                $("[data-field = 'catalog']").children().each(function () {
                    if ($(this).text() == cataCode) {
                        $(this).text(cataCodeName);
                    }
                })

            }

        });
    };
});



//新增中的新增产品附件、备选 供应商
table.on('toolbar(asuppliertable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    let data = checkStatus.data;
    switch (obj.event) {
        case 'new':       //规格型号新增
            layer.open({
                type: 2,
                area: ['908px', '380px'],
                content: 'views/jsp/BasicData/tpl/newupasupplier.jsp'
            });
            break;
        case 'delet'://规格型号删除
            let delid = [];
            for (var i = 0; i < data.length; i++) {
                delid.push(data[i].id)
            }
            if (delid.length == 0) {
                layer.msg("请选择要删除的数据");
                break;
            }
            if (delgys(delid)) {
                layer.msg("删除成功");
                refrash_gys();
            } else {
                layer.msg("删除失败");
            }
            break;
    };
    return false;
});

table.on('tool(asuppliertable)', function(obj){
    let data = obj.data;
    if(obj.event === 'asupplierup') {
        layer.open({
            type: 2,
            area: ['908px', '380px'],
            content: 'views/jsp/BasicData/tpl/newupasupplier.jsp?id='+obj.data.id
        });
    }else if(obj.event === 'asupplierde') {
        layer.confirm('确认删除?', function (index) {
            let delid = [];
            delid.push(data.id);
            if(delgys(delid)){
                layer.msg("删除成功");
                obj.del();
            }else{
                layer.msg("删除失败");
            }

            layer.close(index);
        });
    }
});

//批量删除备选供应商
function delgys(ids) {
    let tf = false;
    $.ajax({
        type: 'post',
        data: {"ids": JSON.stringify(ids)},
        url: 'productfjgysbak/delgys',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data > 0;

            }
        }
    });
    return tf;
}

function refrash_gys() {
    table.reload('asuppliertableid',{
        type: "get"
        , url: "productfjgysbak/selectByPage"
        , where: {
            "productCode": code,
            "fjCode":  fjCode
        }
        ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
    }, 'data');
}


//---日志
table.render({
    elem: '#infoselect'
    ,type:"get"
    ,url:"productlog/selectByPage"
    ,where:{
        "code":code
    }
    ,cols: [[
        {field:'type', title:'操作类型', sort: true}
        ,{field:'optioner', title:'操作员名称', sort: true}
        ,{field:'time', title:'更新日期',  sort: true}
        ,{field:'content', title:'操作内容', sort: true}
    ]]
    ,id: 'infoselecttableid'
    ,page: true
    ,height:350
});

//监听提交---保存
form.on('submit(form-save)', function(data){
    //成品新增 (1:成品 2:配件)
    data.field["productType"] = 2;
    //主信息保存
    let parentDataSaveFlag = savemain(data.field);
    if(parentDataSaveFlag){
        layer.msg('保存成功');
    }else{
        layer.msg('保存失败');
    }
    return false;
});

//可用于修改动态生成 图片
$("#newimg").on('click',function () {
    img_count ++;
    var newImg ='<div class="img_tj">'+
                    '<div class="img_wdiv"><img src="statics/images/layui-logo.jpg" id="imgUpload_'+img_count+'"></div>'+
                    '<div class="de_div">'+
                       /* '<input name="img_instructions'+img_count+'" class="layui-input" placeholder="图片说明">'+*/
                        '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_'+img_count+'"></i>'+
                    '</div>'+
                '</div>';
    $('#addimgdiv').append(newImg);
    uploadImgRender("#imgUpload_"+img_count,"#imgUpload_sc_"+img_count);
});

function uploadImgRender(e,uploadimd) {
    var uploadImg = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"productimg"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                console.log(uploadImg);
                $(e).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status != 200) {
                return layer.msg('上传失败');
            }
            var ftpPath = res.data[0].ftpPath;
            var fileName = res.data[0].fileName;
            var src = getFtpPath(ftpPath, fileName);
            imgs.push(src);
            return layer.msg('上传成功');
        }
        , error: function () {
            //演示失败状态，并实现重传
            var img_wdiv = $(e).parent();
            var img_sb = img_wdiv.find('.img_sb');
            if (img_sb.length == 0) {
                img_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                img_wdiv.find('.demo-reload').on('click', function () {
                    uploadImg.upload();
                });
            }
        }
    });

    $(uploadimd).on('click',function () {
        let pathD=$(e).attr("src")
        for (let i = 0; i <imgs.length ; i++) {
            if (imgs[i]==pathD){
                imgs.splice(i,1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
}

//文件
$("#newfile").on('click',function () {
    file_count ++;
    var newFile ='<div class="img_tj">'+
      '<div class="file_wdiv"><div style="height: 25px;"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="file_span'+file_count+'" id="file_span'+file_count+'" '+
        '   onclick="getPathOnLine(this);"></a>&nbsp;</div>' +
       // '<a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="file_span'+file_count+'" id="file_span'+file_count+'"></a>' +
        '<a type="button" class="layui-btn" id="fileUpload_'+file_count+'">  ' +
        ' <i class="layui-icon"></i>上传附件</a></div>'+
      '<div class="de_div">'+
      '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;"  id="fileUpload_sc_'+file_count+'"></i>'+

        '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;display: none;"   id="fileDownload_sc_'+file_count+'" ></i>'+
      '</div>'+
      '</div>';

    $('#addfilediv').append(newFile);
    uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count,"#fileDownload_sc_"+file_count);
});
function getPathOnLine(path){
    for(var i=0;i<wjs.length;i++){
        var ph=wjs[i];
        if(ph.indexOf(path.text)!=-1){
            var filename=ph.split("filename=")[1];
            var filenames=ph.split("pathname=")[1].split("&filename=");
            var pathA=filenames[0];//"c:/a/a/"
            var fnas=filenames[1].split("&originalFileName=");
            filename=fnas[1];
            pathA=pathA+"/"+fnas[0];
            onLineFile(pathA);
        }
    }

}
function uploadFileRender(e,uploadimd,name,download) {
    var uploadfile = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"productwj"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(name).html(file.name);
                $(name).attr("title",file.name);
                $(download).css("display","block");
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status !=200) {
                return layer.msg('上传失败');
            }
            var ftpPath=res.data[0].ftpPath;
            var fileName=res.data[0].fileName;
            var originalFileName=res.data[0].originalFileName;
            fileName=fileName+"&originalFileName="+originalFileName;
            var src=getFtpPath(ftpPath,fileName);
            wjs.push(src);
            return layer.msg('上传成功');

        }
        , error: function () {
            //演示失败状态，并实现重传
            var file_wdiv = $(e).parent();
            var img_sb = file_wdiv.find('.img_sb');
            if(img_sb.length == 0){
                file_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                file_wdiv.find('.demo-reload').on('click', function () {
                    uploadfile.upload();
                });
            }
        }
    });


//移除
    $(uploadimd).on('click',function () {
        let pathD=$(name)[0].innerText;
        for (let i = 0; i <wjs.length ; i++) {
            if (wjs[i].indexOf(pathD)){
                wjs.splice(i,1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
    //下载
    $(download).on('click',function () {
        downFileload2($(name)[0].href,$(name)[0].text);
    })
}
function savemain(data) {
    if(id !="") data.id=id;
    maincode=data.code;
    data.cataCode=productTreeList.getValue('valueStr');//所属目录
    for (let i in selectdata) {
        if (data.cataCode==selectdata[i].code){
            data.upCataCode=selectdata[i].path;//上级目录
            break;
        }
    }
    window.sessionStorage.setItem("code",maincode);
    code=window.sessionStorage.getItem("code");
    data.img=JSON.stringify(imgs);
    data.wj=JSON.stringify(wjs);
    var tf=false;
    $.ajax({
        type : 'post',
        data:JSON.stringify(data),
        url:'productmaininfo/savemain',
        dataType:"json",
         contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf= da.data >0 ;
                id=da.data;//
            }
        }
    });
    return tf;
}
//关闭
$("#shutdown").on('click',function () {
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/product.jsp");
        parent.intab("views/jsp/BasicData/product.jsp","产品")
        parent.detab("views/jsp/BasicData/tpl/newupproduct.jsp"+(id==''?'':'?id='+id),"修改产品");
    },1000)
})

//图片、文件上传
function upload() {
    upload.render({
        elem: '#logoadd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"customerlogo"}//头像
        ,before: function(obj) {

        }
        ,done: function(res){
            //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                $("#userphotos").attr('src',src);
                $("input[name='logo']")[0].value=src;
            }
            //上传成功
        }
    })
}
function delfjinfo(ids) {
    var tf=false;
    $.ajax({
        type : 'post',
        data:{"ids":JSON.stringify(ids)},
        url:'productfjinfo/delfjinfo',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf= da.data >0 ;

            }
        }
    });
    return tf;
}
function refrash() {
    table.reload('producttableid', {
        type:"get"
        ,url:"productfjinfo/selectByPage"
        ,where:{
            "code":code
        },
        page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
}
//获取所有供应商
function  getgys() {
    var gys=[];
    $.ajax({
        type : 'get',
        url:'customer2/getAllGys',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                for(var i=0;i<da.data.length;i++){
                    var obj={};
                    obj.code=da.data[i].code;
                    obj.name=da.data[i].name;
                    gys.push(obj);
                }

            }
        }
    });
    return gys;
}
function  getoption(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}
function  getoptionHs(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"["+objs[i].code+"]</option>";
    }
    return stoptions;
}

function  isExisCode(obj) {
    $.ajax({
        type : 'get',
        data:{"code":$("input[name='code']")[0].value},
        url:'productmaininfo/isexit',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
               if(da.data){
                   layer.msg("编码重复，重新输入");
                   $("input[name='code']")[0].value="";
                    $("#code").focus();
               }

            }
        }
    });
}


function queryPid() {
    $.ajax({
        type : 'get',
        url:'productcatalog/getProductDirectoryInfo',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                selectdata=da.data;

            }
        }
    });
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/; //非负浮点数
    let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["children"]){
            tmparr["children"]=  getAllJson(item["children"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }
    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: true,
        filterable: true,
        radio: true,
        tree: {
            show: true,
            showFolderIcon: true,
            showLine: true,
            indent: 20,
            expandedKeys: [ -3 ],
            strict: false,
        },
        height: '300px',
        data: data,
        on: function(data){
            if(data.isAdd){
                return data.change.slice(0, 1)
            }
        },
    });
}
//json转tree
function toTree(data) {
    let result = []
    if(!Array.isArray(data)) {
        return result
    }
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if(parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}


